package com.hushao.aimi.controller;

import com.hushao.aimi.ValidUtil;
import com.hushao.aimi.common.ResponseCode;
import com.hushao.aimi.common.ServerResponse;
import com.hushao.aimi.vo.UserVo;
import com.hushao.aimi.service.UserService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * @description: 用户控制器
 * @author: 胡少
 * @create: 2018-06-03 21:46
 **/
@RestController
@RequestMapping("/u")
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping("/noLogin")
    @ApiOperation(value = "没有登录")
    public ServerResponse needLogin(){
        return ServerResponse.Error(ResponseCode.UNAUTHORIZED.getCode(),"没有登录");
    }

    /**
     * 获取用户列表（分页）
     * @param username
     * @param pageable
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "获取用户列表")
    @GetMapping
    public ServerResponse getUserByNameLike(@RequestParam(value = "username",required = false,defaultValue = "")String username,
                                                Pageable pageable)throws Exception{
        return userService.findAllByUsernameLike(username,pageable);
    }

    /**
     * 获取个人信息
     * @param username
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "获取个人")
    @GetMapping("/{username}")
    public ServerResponse getUser(@PathVariable(value = "username") String username)throws Exception{
        return userService.getUser(username);
    }

    /**
     * 添加用户
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "添加用户")
    @PostMapping
    public ServerResponse addUser(@RequestBody UserVo user)throws Exception{
        return userService.addUser(user);
    }

    /**
     * 删除用户
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "删除用户")
    @DeleteMapping("/{userId}")
    public ServerResponse delUser(@PathVariable(value = "userId") String userId)throws Exception{
        return userService.delUser(userId);
    }

    /**
     * 修改用户
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "修改用户")
    @PutMapping
    public ServerResponse updateUser(@Valid @RequestBody UserVo user,BindingResult bindingResult)throws Exception{
        ValidUtil.valid(bindingResult);
        return userService.update(user);
    }
}
